/*
 * Copyright Thoughtworks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import classNames from "classnames/bind";
import { MithrilViewComponent } from "jsx/mithril-component";
import m from "mithril";
import styles from "./index.scss";
import { i18n } from "helpers/i18n";

const classnames = classNames.bind(styles);

// Epic-10: 为 site-menu 组件添加翻译加载支持
let siteMenuTranslationsLoaded = false;

/**
 * 确保 site-menu 翻译已加载
 */
async function ensureSiteMenuTranslationsLoaded(): Promise<void> {
  if (!siteMenuTranslationsLoaded) {
    try {
      await i18n.loadPageTranslations("site-menu");
      siteMenuTranslationsLoaded = true;
      console.log("Successfully loaded site-menu translations");
    } catch (error) {
      console.warn("Failed to load site-menu translations:", error);
      // 即使加载失败，也标记为已尝试，避免重复尝试
      siteMenuTranslationsLoaded = true;
    }
  }
}

const activeItem = (href?: string): boolean => {
  if (!!href) {
    return new URL(href, window.location.origin).pathname === window.location.pathname;
  } else {
    return false;
  }
};

interface SiteHeaderLinkAttrs {
  isNavLink?: boolean;
  target?: string;
  href?: string;
}

class SiteHeaderLink extends MithrilViewComponent<SiteHeaderLinkAttrs> {
  view(vnode: m.Vnode<SiteHeaderLinkAttrs>) {
    const classes = classnames({
      [styles.siteNavLink]: vnode.attrs.isNavLink,
      [styles.siteSubNavLink]: !vnode.attrs.isNavLink,
      [styles.active]: !vnode.attrs.isNavLink && activeItem(vnode.attrs.href),
    });

    return (
      <a class={classes} href={vnode.attrs.href || "#"} target={vnode.attrs.target || ""}>
        {vnode.children}
      </a>
    );
  }
}

interface Text {
  text?: string;
}

interface TextWithLink extends Text {
  href?: string;
}

interface SiteNavItemAttrs extends TextWithLink {
  isDropDown?: boolean;
}

class SiteNavItem extends MithrilViewComponent<SiteNavItemAttrs> {
  view(vnode: m.Vnode<SiteNavItemAttrs>) {
    const dropDownClass = classnames(
      {
        [styles.isDropDown]: vnode.attrs.isDropDown,
        [styles.active]: activeItem(vnode.attrs.href) || this.isActive(vnode),
      },
      styles.siteNavItem
    );

    if (!vnode.attrs.isDropDown) {
      return (
        <li class={dropDownClass}>
          <SiteHeaderLink href={vnode.attrs.href} isNavLink={true}>
            {vnode.attrs.text}
          </SiteHeaderLink>
        </li>
      );
    }

    return (
      <li class={dropDownClass}>
        <SiteHeaderLink isNavLink={true}>{vnode.attrs.text}</SiteHeaderLink>
        <i class={styles.caretDownIcon} />
        {vnode.children}
      </li>
    );
  }

  isActive(vnode: m.Vnode<SiteNavItemAttrs>) {
    if (!vnode.attrs.isDropDown || !vnode.attrs.text) {
      return false;
    }
    return window.location.pathname.toLowerCase().startsWith(`/go/${vnode.attrs.text.toLowerCase()}`);
  }
}

class SiteSubNav extends MithrilViewComponent<{}> {
  view(vnode: m.Vnode<{}>) {
    return <ul class={styles.siteSubNav}>{vnode.children}</ul>;
  }
}

export class SiteSubNavItem extends MithrilViewComponent<TextWithLink> {
  view(vnode: m.Vnode<TextWithLink>) {
    return (
      <li class={styles.siteSubNavItem}>
        <SiteHeaderLink href={vnode.attrs.href} isNavLink={false}>
          {vnode.attrs.text}
        </SiteHeaderLink>
      </li>
    );
  }
}

class SiteSubNavHeading extends MithrilViewComponent<Text> {
  view(vnode: m.Vnode<Text>) {
    return (
      <li class={styles.siteSubNavItem}>
        <h5 class={styles.siteSubNavLinkHead}>{vnode.attrs.text}</h5>
      </li>
    );
  }
}

export interface Attrs {
  canViewTemplates: boolean;
  isGroupAdmin: boolean;
  isUserAdmin: boolean;
  canViewAdminPage: boolean;
  showAnalytics: boolean;
}

export class SiteMenu extends MithrilViewComponent<Attrs> {
  oninit() {
    // Epic-10: 确保 site-menu 翻译已加载
    ensureSiteMenuTranslationsLoaded();
  }

  view(vnode: m.Vnode<Attrs>) {
    const analyticsMenu: m.Children = vnode.attrs.showAnalytics ? (
      <SiteNavItem href="/go/analytics" text={i18n.tSyncForPage("navigation.analytics", "site-menu")} />
    ) : null;

    let adminMenu = null;
    if (vnode.attrs.canViewAdminPage) {
      if (vnode.attrs.isUserAdmin) {
        adminMenu = (
          <SiteNavItem isDropDown={true} text={i18n.tSyncForPage("navigation.admin", "site-menu")}>
            <div class={styles.subNavigation}>
              <SiteSubNav>
                <SiteSubNavItem href="/go/admin/pipelines" text={i18n.tSyncForPage("admin.pipelines", "site-menu")} />
                <SiteSubNavItem
                  href="/go/admin/environments"
                  text={i18n.tSyncForPage("admin.environments", "site-menu")}
                />
                <SiteSubNavItem href="/go/admin/templates" text={i18n.tSyncForPage("admin.templates", "site-menu")} />
                <SiteSubNavItem href="/go/admin/config_xml" text={i18n.tSyncForPage("admin.config_xml", "site-menu")} />
                <SiteSubNavItem
                  href="/go/admin/package_repositories/new"
                  text={i18n.tSyncForPage("admin.package_repositories", "site-menu")}
                />
              </SiteSubNav>
              <SiteSubNav>
                <SiteSubNavItem
                  href="/go/admin/elastic_agent_configurations"
                  text={i18n.tSyncForPage("admin.elastic_agent_configurations", "site-menu")}
                />
                <SiteSubNavItem
                  href="/go/admin/config_repos"
                  text={i18n.tSyncForPage("admin.config_repos", "site-menu")}
                />
                <SiteSubNavItem
                  href="/go/admin/artifact_stores"
                  text={i18n.tSyncForPage("admin.artifact_stores", "site-menu")}
                />
                <SiteSubNavItem
                  href="/go/admin/secret_configs"
                  text={i18n.tSyncForPage("admin.secret_configs", "site-menu")}
                />
                <SiteSubNavItem href="/go/admin/scms" text={i18n.tSyncForPage("admin.scms", "site-menu")} />
              </SiteSubNav>
              <SiteSubNav>
                <SiteSubNavHeading text={i18n.tSyncForPage("admin.server_configuration", "site-menu")} />
                <SiteSubNavItem
                  href="/go/admin/config/server"
                  text={i18n.tSyncForPage("admin.server_configuration", "site-menu")}
                />
                <SiteSubNavItem
                  href="/go/admin/maintenance_mode"
                  text={i18n.tSyncForPage("admin.maintenance_mode", "site-menu")}
                />
                <SiteSubNavItem href="/go/admin/backup" text={i18n.tSyncForPage("admin.backup", "site-menu")} />
                <SiteSubNavItem href="/go/admin/plugins" text={i18n.tSyncForPage("admin.plugins", "site-menu")} />
              </SiteSubNav>
              <SiteSubNav>
                <SiteSubNavHeading text={i18n.tSyncForPage("admin.security", "site-menu")} />
                <SiteSubNavItem
                  href="/go/admin/security/auth_configs"
                  text={i18n.tSyncForPage("admin.authorization_configuration", "site-menu")}
                />
                <SiteSubNavItem
                  href="/go/admin/security/roles"
                  text={i18n.tSyncForPage("admin.role_configuration", "site-menu")}
                />
                <SiteSubNavItem
                  href="/go/admin/users"
                  text={i18n.tSyncForPage("admin.users_management", "site-menu")}
                />
                <SiteSubNavItem
                  href="/go/admin/admin_access_tokens"
                  text={i18n.tSyncForPage("admin.access_tokens_management", "site-menu")}
                />
              </SiteSubNav>
            </div>
          </SiteNavItem>
        );
      } else if (vnode.attrs.isGroupAdmin) {
        adminMenu = (
          <SiteNavItem isDropDown={true} text={i18n.tSyncForPage("navigation.admin", "site-menu")}>
            <div class={classnames(styles.subNavigation, styles.hasOnlyOneOption)}>
              <SiteSubNav>
                <SiteSubNavItem href="/go/admin/pipelines" text={i18n.tSyncForPage("admin.pipelines", "site-menu")} />
                <SiteSubNavItem
                  href="/go/admin/environments"
                  text={i18n.tSyncForPage("admin.environments", "site-menu")}
                />
                <SiteSubNavItem href="/go/admin/templates" text={i18n.tSyncForPage("admin.templates", "site-menu")} />
                <SiteSubNavItem
                  href="/go/admin/pipelines/snippet"
                  text={i18n.tSyncForPage("admin.config_xml", "site-menu")}
                />
                <SiteSubNavItem href="/go/admin/plugins" text={i18n.tSyncForPage("admin.plugins", "site-menu")} />
                <SiteSubNavItem
                  href="/go/admin/package_repositories/new"
                  text={i18n.tSyncForPage("admin.package_repositories", "site-menu")}
                />
                <SiteSubNavItem
                  href="/go/admin/config_repos"
                  text={i18n.tSyncForPage("admin.config_repos", "site-menu")}
                />
                <SiteSubNavItem
                  href="/go/admin/elastic_agent_configurations"
                  text={i18n.tSyncForPage("admin.elastic_agent_configurations", "site-menu")}
                />
                <SiteSubNavItem href="/go/admin/scms" text={i18n.tSyncForPage("admin.scms", "site-menu")} />
              </SiteSubNav>
            </div>
          </SiteNavItem>
        );
      } else if (vnode.attrs.canViewTemplates) {
        adminMenu = (
          <SiteNavItem isDropDown={true} text={i18n.tSyncForPage("navigation.admin", "site-menu")}>
            <div class={classnames(styles.subNavigation, styles.hasOnlyOneOption)}>
              <SiteSubNav>
                <SiteSubNavItem
                  href="/go/admin/environments"
                  text={i18n.tSyncForPage("admin.environments", "site-menu")}
                />
                <SiteSubNavItem href="/go/admin/templates" text={i18n.tSyncForPage("admin.templates", "site-menu")} />
                <SiteSubNavItem
                  href="/go/admin/config_repos"
                  text={i18n.tSyncForPage("admin.config_repos", "site-menu")}
                />
                <SiteSubNavItem
                  href="/go/admin/elastic_agent_configurations"
                  text={i18n.tSyncForPage("admin.elastic_agent_configurations", "site-menu")}
                />
              </SiteSubNav>
            </div>
          </SiteNavItem>
        );
      }
    } else {
      //Normal users now too have access to environments and config-repo!!
      adminMenu = (
        <SiteNavItem isDropDown={true} text={i18n.tSyncForPage("navigation.admin", "site-menu")}>
          <div class={classnames(styles.subNavigation, styles.hasOnlyOneOption)}>
            <SiteSubNav>
              <SiteSubNavItem
                href="/go/admin/environments"
                text={i18n.tSyncForPage("admin.environments", "site-menu")}
              />
              <SiteSubNavItem
                href="/go/admin/config_repos"
                text={i18n.tSyncForPage("admin.config_repos", "site-menu")}
              />
              <SiteSubNavItem
                href="/go/admin/elastic_agent_configurations"
                text={i18n.tSyncForPage("admin.elastic_agent_configurations", "site-menu")}
              />
            </SiteSubNav>
          </div>
        </SiteNavItem>
      );
    }

    return (
      <nav class={styles.mainMenu}>
        <ul class={styles.siteNav}>
          <SiteNavItem href="/go/pipelines" text={i18n.tSyncForPage("navigation.dashboard", "site-menu")} />
          <SiteNavItem href="/go/agents" text={i18n.tSyncForPage("navigation.agents", "site-menu")} />
          <SiteNavItem href="/go/materials" text={i18n.tSyncForPage("navigation.materials", "site-menu")} />
          {analyticsMenu}
          {adminMenu}
        </ul>
      </nav>
    );
  }
}
